<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessageBox, ElMessage } from 'element-plus'

import { Table } from '@/components/Table'

import {
  spDieOrderListApi,
  spDieOrderDelApi,
  spDieOrderEditApi,
  spDieOrderAddAdminApi,
  spDieOrderConfirmApi
} from '@/api/sp/die'

import { sysDictRelsApi } from '@/api/dict'

import { useTable } from '@/hooks/web/useTableTest'
import {
  // h,
  ref,
  unref,
  reactive
} from 'vue'
import See from './components/See.vue'
import Edit from './components/Edit.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'
// 获取字典
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}
const dictRelsData = ref() // 联动数据
const searchRef = ref() // 搜索的标签

const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
const iconDelete = useIcon({ icon: 'material-symbols:delete-outline' })
const iconCompleted = useIcon({ icon: 'fluent-mdl2:completed' })

const defaultTime = ref<[Date, Date]>([
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59)
])

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: spDieOrderListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'pasture_org_name',
    label: '所属牧场',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'code',
    label: '编号',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'number',
    label: '数量',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'die_time',
    label: '死亡时间',
    width: 200,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        defaultTime: defaultTime
      }
    }
  },
  {
    field: 'type',
    label: '死亡类型',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('die_type', cellValue)
    },
    width: 150,
    search: {
      component: 'Select',
      componentProps: {
        options: dict.die_type
      },
      show: true
    },
    table: {
      show: true
    }
  },
  {
    field: 'state',
    label: '状态',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('die_state', cellValue)
    },
    table: {
      show: true
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.die_state
      },
      show: true
    }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 200,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        defaultTime: defaultTime
      }
    }
  },
  {
    field: 'note',
    label: '备注',
    width: 150,
    table: {
      show: true
    }
  },
  {
    field: 'action',
    width: 200,
    fixed: 'right',
    label: '操作',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

// 删除
const apiDel = async (id) => {
  let delRes = await spDieOrderDelApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
}

// 审核
const apicheck = async (id) => {
  let delRes = await spDieOrderConfirmApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
}

// 完结
const ok = async (id) => {
  let okRes = await spDieOrderConfirmApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (okRes) {
    getList()
  }
}
const action = async (type: string, row: any = {}) => {
  actionType.value = type

  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0'
      }
      // tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm('确定要删除这个死亡记录单吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiDel(Number(row.id))
        })
        .catch(() => {})
      break
    case 'shen':
      ElMessageBox.confirm('确定要审核吗？', '审核', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apicheck(Number(row.id))
        })
        .catch(() => {})
      break
    case 'ok':
      ElMessageBox.confirm('确定完结吗？', '完结', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          ok(row.id)
        })
        .catch(() => {})
      break
    default:
      console.log('未知类型')
  }
}

const editRef = ref()
const loading = ref(false)
const checkedAll = ref(false)
const ids = ref([])
const save = async () => {
  const edit: any = unref(editRef)
  const dataInfo = await edit?.data
  const methods = await edit?.methods
  const getFormData = await edit?.getFormData()
  const { getSelections } = methods
  let selectDataInfo = ref({})
  if (dataInfo.number > 0) {
  } else {
    ElMessage.error('所选资产不能为0')
  }
  await getSelections().then((res) => {
    selectDataInfo.value = res
    checkedAll.value = res.allCheck.value ? res.allCheck.value : false
    if (res.allCheck.value) {
      if (res.noSelectData.value.length > 0) {
        ids.value = res.noSelectData.value.map((element) => element.id)
      }
    } else {
      if (res.selectData.value.length > 0) {
        ids.value = res.selectData.value.map((element) => element.id)
      }
    }
  })
  switch (actionType.value) {
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          const getFormData = await edit?.getFormData()
          loading.value = false
          // const data = (await edit?.getFormData()) as any
          let res = await spDieOrderEditApi({
            my_dept_id: wsCache.get('userInfo').default_dept_id,
            asset_code: dataInfo.asset_code,
            earcon_code: dataInfo.earcon_code,
            ...getFormData,
            checkedAll: checkedAll.value,
            selected: ids.value
          })
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          const resIn = await spDieOrderAddAdminApi({
            my_dept_id: wsCache.get('userInfo').default_dept_id,
            asset_code: dataInfo.asset_code,
            earcon_code: dataInfo.earcon_code,
            ...getFormData,
            checkedAll: checkedAll.value,
            selected: ids.value
          })
            .catch(() => {})
            .finally(() => {})
          if (resIn) {
            dialogVisible.value = false
            getList()
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}

// 调度定时器任务
const init = async () => {
  // 列表查询
  await getList()
  // 获取关联关系
  await getDictRels()
}
init()
</script>

<template>
  <ContentWrap>
    <Search
      ref="searchRef"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :loading="tableObject.loading"
      :data="tableObject.tableList"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
      :selection="false"
    >
      <template #action="{ row }">
        <ElButton
          circle
          v-if="row.state === '1'"
          :icon="iconEdit"
          @click="action('edit', row)"
          title="编辑"
        />
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="查看" />
        <ElButton
          circle
          v-if="row.state === '1'"
          :icon="iconDelete"
          @click="action('del', row)"
          title="删除"
        />
        <ElButton
          v-if="row.state === '1'"
          circle
          :icon="iconCompleted"
          @click="action('ok', row)"
          title="理赔完结"
        />
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit v-if="actionType == 'add'" ref="editRef" />
    <Edit v-if="actionType == 'edit'" ref="editRef" :current-row="tableObject.currentRow" />
    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      :id="tableObject.currentRow.id"
    />
    <template #footer>
      <ElButton
        v-if="actionType !== 'see' && actionType !== 'add'"
        type="primary"
        :loading="loading"
        @click="save()"
      >
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton v-if="actionType == 'add'" type="primary" :loading="loading" @click="save()">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
